<template>
 <div>
  <van-nav-bar
  title="登录"
/>
<!--
  登录表单
  点击登录按钮的时候，会触发submit事件
  -->
  <van-form>
    <van-field
    v-model="mobile"
    label="手机号"
    placeholder="请输入手机号"
    :rules="rules.mobile"
  />
    <van-field
    v-model="code"
    label="验证码"
    placeholder="请输入验证码"
    :rules="rules.code"
  />
    <div style="margin: 16px;">
    <van-button round block @click="onSubmit" :disabled="isLoading" :loading="isLoading" loading-text="登陆中..." type="info" native-type="submit">
      登录
    </van-button>
  </div>
  </van-form>
 </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      code: '246810',
      mobile: '13912345678',
      isLoading: false,
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'onBlur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'onBlur'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'onBlur' },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误',
            trigger: 'onBlur'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async onSubmit() {
      console.log(111)
      this.isLoading = true
      try {
        const res = await userLogin(this.mobile, this.code)
        console.log('登录成功', res)
        this.$toast.success('登录成功')
        this.setToken(res.data.data)
        console.log(this.$route)
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('/')
        }
      } catch {
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
